package com.hanson.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.GoodsCommentBean;
import com.hanson.entity.UserBean;
import com.hanson.mapper.GoodsCommentBeanMapper;
import com.hanson.mapper.UserBeanMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.text.DecimalFormat;
import java.util.*;

@Service
public class GoodsCommentService {
    @Autowired
    private GoodsCommentBeanMapper goodsCommentBeanMapper;
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private OrderService orderService;

    @Transactional(rollbackFor = Exception.class)
    public void addComment(GoodsCommentBean goodsCommentBean, String openId) {
        String comment = goodsCommentBean.getComment();
        goodsCommentBean.setComment(null);
        goodsCommentBean.setCreateDate(new Date());
        goodsCommentBean.setOpenId(openId);
        if (StringUtils.isNotEmpty(openId)) {
            UserBean userBean = userBeanMapper.selectByOpenId(openId);
            if (null != userBean) {
                goodsCommentBean.setUserName(StringUtils.isNotEmpty(userBean.getUserName()) ? userBean.getUserName() : userBean.getNickName());
                goodsCommentBean.setUserImage(userBean.getHeadImg());
            }
        }

        int star1 = null == goodsCommentBean.getStar1() ? 0 : goodsCommentBean.getStar1();
        int star2 = null == goodsCommentBean.getStar2() ? 0 : goodsCommentBean.getStar2();
        int star = star1 + star2 / 2;
        if (star >= 4) {
            goodsCommentBean.setScore(1);
        } else if (star >= 2) {
            goodsCommentBean.setScore(2);
        } else {
            goodsCommentBean.setScore(3);
        }
        Integer maxSort = goodsCommentBeanMapper.selectMaxSort(goodsCommentBean.getGoodsId());
        maxSort = null == maxSort ? 1 : maxSort + 1;
        goodsCommentBean.setSort(maxSort);
        goodsCommentBeanMapper.insert(goodsCommentBean);
        if (StringUtils.isNotEmpty(comment)) {
            String commentSql = "update t_goods_comment set comment=? where id=?";
            jdbcTemplate.execute("set names utf8mb4");
            jdbcTemplate.update(commentSql, comment, goodsCommentBean.getId());
        }
        if (StringUtils.isNotEmpty(goodsCommentBean.getOrderId())) {
            orderService.finishOrder(goodsCommentBean.getOrderId());
        }
    }

    public void topComment(int commentId) {
        GoodsCommentBean goodsCommentBean = goodsCommentBeanMapper.selectByPrimaryKey(commentId);
        if (null != goodsCommentBean) {
            Integer maxSort = goodsCommentBeanMapper.selectMaxSort(goodsCommentBean.getGoodsId());
            maxSort = null == maxSort ? 1 : maxSort + 1;
            goodsCommentBeanMapper.updateSortById(maxSort, goodsCommentBean.getId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateComment(GoodsCommentBean goodsCommentBean) {
        if (null != goodsCommentBean) {
            GoodsCommentBean returnBean = goodsCommentBeanMapper.selectByPrimaryKey(goodsCommentBean.getId());
            if (null != returnBean) {
                returnBean.setOpenId(goodsCommentBean.getOpenId());
                returnBean.setGoodsId(goodsCommentBean.getGoodsId());
                returnBean.setStar1(goodsCommentBean.getStar1());
                returnBean.setStar2(goodsCommentBean.getStar2());
                int star1 = null == goodsCommentBean.getStar1() ? 0 : goodsCommentBean.getStar1();
                int star2 = null == goodsCommentBean.getStar2() ? 0 : goodsCommentBean.getStar2();
                int star = star1 + star2 / 2;
                if (star >= 4) {
                    goodsCommentBean.setScore(1);
                } else if (star >= 2) {
                    goodsCommentBean.setScore(2);
                } else {
                    goodsCommentBean.setScore(3);
                }
                returnBean.setUserName(goodsCommentBean.getUserName());
                returnBean.setUserImage(goodsCommentBean.getUserImage());
                goodsCommentBeanMapper.updateByPrimaryKey(returnBean);
            }
        }
        if (StringUtils.isNotEmpty(goodsCommentBean.getComment())) {
            String commentSql = "update t_goods_comment set comment=? where id=?";
            jdbcTemplate.execute("set names utf8mb4");
            jdbcTemplate.update(commentSql, goodsCommentBean.getComment(), goodsCommentBean.getId());
        }
        if (StringUtils.isNotEmpty(goodsCommentBean.getReply())) {
            String commentSql = "update t_goods_comment set reply=? where id=?";
            jdbcTemplate.execute("set names utf8mb4");
            jdbcTemplate.update(commentSql, goodsCommentBean.getReply(), goodsCommentBean.getId());
        }
    }

    public void reply(GoodsCommentBean goodsCommentBean) {
        if (null != goodsCommentBean && StringUtils.isNotEmpty(goodsCommentBean.getIds())) {
            for (String id : goodsCommentBean.getIds().split(",")) {
                GoodsCommentBean returnBean = goodsCommentBeanMapper.selectByPrimaryKey(Integer.parseInt(id));
                if (null != returnBean) {
                    if (StringUtils.isNotEmpty(goodsCommentBean.getReply())) {
                        String commentSql = "update t_goods_comment set reply=? where id=?";
                        jdbcTemplate.execute("set names utf8mb4");
                        jdbcTemplate.update(commentSql, goodsCommentBean.getReply(), Integer.parseInt(id));
                    }
                }
            }

        }
    }


    public List<GoodsCommentBean> selectByGoodsId(int goodsId, int scoreType, ModelMap modelMap) {
        Map<String, String> countMap = new HashMap<>();
        List<GoodsCommentBean> goodsCommentBeanList = goodsCommentBeanMapper.selectByGoodsId(goodsId);
        List<GoodsCommentBean> returnList = new ArrayList<>();
        List<Integer> totalStar = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(goodsCommentBeanList)) {
            for (GoodsCommentBean c : goodsCommentBeanList) {
                totalStar.add(c.getStar1());
                if (0 == scoreType || c.getScore() == scoreType) {
                    returnList.add(c);
                }
            }
            double avgStarValue = totalStar.stream().mapToDouble(p -> p).average().getAsDouble();
            countMap.put("star", new DecimalFormat("0").format(avgStarValue));
        } else {
            countMap.put("star", "0");
        }

        countMap.put("goodPercent", "0.00%");
        countMap.put("all", "0");
        countMap.put("score1", "0");
        countMap.put("score2", "0");
        countMap.put("score3", "0");
        List<Map<String, Integer>> countList = goodsCommentBeanMapper.countByGoodsId(goodsId);
        if (CollectionUtils.isNotEmpty(countList)) {
            int all = 0;
            for (Map<String, Integer> map : countList) {
                int num = Integer.parseInt(String.valueOf(map.get("num")));
                countMap.put("score" + String.valueOf(map.get("score")), num + "");
                all += num;
            }
            countMap.put("all", all + "");
            countMap.put("goodPercent", BusinessUtil.getPercent(Integer.parseInt(String.valueOf(countMap.get("score1"))), all) + "%");
        }
        modelMap.put("countData", countMap);
        return returnList;
    }

    public Page<GoodsCommentBean> listComments(Page<GoodsCommentBean> page, GoodsCommentBean goodsCommentBean) {
        return page.setRecords(goodsCommentBeanMapper.listComments(goodsCommentBean));
    }

    public void delete(Integer id) {
        goodsCommentBeanMapper.deleteByPrimaryKey(id);
    }

    public GoodsCommentBean selectById(Integer id) {
        return goodsCommentBeanMapper.selectByDetail(id);
    }

    public int updateSort(Integer sort, Integer id) {
        return goodsCommentBeanMapper.updateSortById(sort, id);
    }
}
